// src/models/product.model.js
import { NotFoundError, BadRequestError } from "../utils/errors.js";
import { DataTypes } from "sequelize";
// 商品模型定义
export default (sequelize) => {
  const Product = sequelize.define(
    "Products",
    {
      id: {
        type: DataTypes.CHAR(36), //DataTypes.UUID, // 使用UUID类型
        primaryKey: true,
        allowNull: false,
        defaultValue: DataTypes.UUIDV4, // 或使用 () => uuidv4()
        comment: "商品ID",
      },
      category_id: {
        type: DataTypes.INTEGER, // 或改为与Categories表id相同的类型
        allowNull: false,
        field: "category_id", // 明确指定数据库列名
      },
      name: {
        type: DataTypes.STRING(100),
        allowNull: false,
        validate: {
          len: [2, 100],
          notEmpty: true,
        },
      },
      slug: {
        type: DataTypes.STRING(120),
        allowNull: true, // 改为允许null
        defaultValue: null, // 显式设置默认值（推荐）
        unique: true,
        validate: {
          is: {
            args: /^[a-z0-9-]*$/, // 使用*允许空字符串
            msg: "Slug只能包含小写字母、数字和连字符",
          },
        },
      },
      description: {
        type: DataTypes.TEXT,
        validate: {
          len: [0, 5000],
        },
      },
      price: {
        type: DataTypes.DECIMAL(10, 2),
        allowNull: false,
        validate: {
          isDecimal: true,
          min: 0,
        },
      },
      costPrice: {
        type: DataTypes.DECIMAL(10, 2),
        validate: {
          isDecimal: true,
        },
      },
      stock: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
        validate: {
          isInt: true,
          min: 0,
        },
      },
      skus: {
        type: DataTypes.TEXT, // 使用TEXT类型存储更长的JSON字符串
        unique: true,
        validate: {
          isValidSkus(value) {
            try {
              const skus = JSON.parse(value);
              if (!Array.isArray(skus)) {
                throw new Error("SKU数据必须是数组");
              }
              // 验证每个SKU对象的结构
              skus.forEach((sku) => {
                if (!sku.price || typeof sku.price !== "number") {
                  throw new Error("每个SKU必须包含有效的price字段");
                }
                // 添加其他必要验证...
              });
            } catch (e) {
              throw new Error("无效的SKU数据格式: " + e.message);
            }
          },
        },
      },
      images: {
        type: DataTypes.JSON,
        defaultValue: [],
        validate: {
          isValidImages(value) {
            if (!Array.isArray(value)) {
              throw new Error("图片必须是数组");
            }
            value.forEach((img) => {
              if (typeof img !== "string" || !img.startsWith("http")) {
                throw new Error("图片必须是有效的URL数组");
              }
            });
          },
        },
      },
      spec: {
        type: DataTypes.JSON,
        defaultValue: {},
      },
      status: {
        type: DataTypes.ENUM("draft", "published", "archived"),
        defaultValue: "draft",
      },
      isFeatured: {
        type: DataTypes.BOOLEAN,
        defaultValue: false,
      },
      salesCount: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
      },
      viewCount: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
      },
      metaTitle: {
        type: DataTypes.STRING(100),
      },
      metaDescription: {
        type: DataTypes.STRING(200),
      },
      category_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: "Categories",
          key: "id",
        },
      },
    },
    {
      tableName: "product",
      timestamps: true,
      paranoid: true, // 启用软删除
      indexes: [
        { fields: ["name"] },
        { fields: ["skus"] },
        { fields: ["category_id"] },
        { fields: ["status"] },
        {
          type: "FULLTEXT",
          fields: ["name", "description"],
        },
      ],
      hooks: {
        beforeValidate: (product) => {
          if (product.name && !product.slug) {
            product.slug = product.name
              .toLowerCase()
              .replace(/[^\w\s]/gi, "")
              .replace(/\s+/g, "-");
          }
        },
      },
    }
  );

  // 关联分类
  Product.associate = (models) => {
    Product.hasMany(models.Sku, {
      foreignKey: "product_id",
      as: "productSkus",
    });
    Product.hasMany(models.SpecValue, {
      foreignKey: "product_id", // 使用数据库中实际的列名
      as: "specValues",
    });

    Product.belongsToMany(models.SpecType, {
      through: {
        model: models.SkuSpec,
        unique: false,
      },
      foreignKey: "sku_id", // 使用中间表的sku_id作为外键
      otherKey: "spec_type_id",
      as: "specTypes",
    });

    Product.belongsTo(models.Category, {
      foreignKey: "category_id",
      as: "category",
      onDelete: "RESTRICT", // 防止误删分类导致商品数据异常[6](@ref)
    });
  };

  // 实例方法：增加浏览量
  Product.prototype.incrementViewCount = async function () {
    this.viewCount += 1;
    await this.save();
  };

  // 类方法：验证商品是否存在
  Product.validateExists = async function (id) {
    const product = await this.findByPk(id, { paranoid: false });
    if (!product) {
      throw new NotFoundError("商品不存在");
    }
    return product;
  };

  // 类方法：检查SKU唯一性
  Product.checkSkuUnique = async function (sku, excludeId = null) {
    const where = { sku };
    if (excludeId) {
      where.id = { [sequelize.Op.ne]: excludeId };
    }

    const exists = await this.findOne({ where });
    if (exists) {
      throw new BadRequestError("SKU已存在");
    }
  };

  return Product;
};
